<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑门店' : '添加门店' }}</span>
      </div>

      <!-- 表单 -->
      <el-form size="mini" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="门店名称" prop="name">
          <el-input class="elinput" v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input class="elinput" v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input class="elinput" v-model="ruleForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="门店介绍" prop="intro">
          <WangEditor :content="ruleForm.intro" @handeleHtml="handleIntroHtml"></WangEditor>
        </el-form-item>
        <el-form-item label="营业时间" prop="startTime">
          <el-time-picker v-model="ruleForm.startTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="开始时间"> </el-time-picker>
          <span style="margin: 0 10px">-</span>
          <el-time-picker v-model="ruleForm.endTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="结束时间"> </el-time-picker>
        </el-form-item>
        <el-form-item label="服务范围" prop="services">
          <el-select v-model="ruleForm.services" placeholder="请选择">
            <el-option 
              v-for="item in serviceList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店logo" prop="logo">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="店主" prop="username">
          <el-input class="elinput" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { add, getStore, getServiceList } from '@/api/stores'
import WangEditor from '@/components/WangEditor.vue'
export default {
  name: 'StoresAdd',
  components: { WangEditor },
  data() {
    return {
      imageUrl: '',
      isEdit: false,
      serviceList: [], // 服务范围列表
      ruleForm: {
        id: 0,
        name: '',
        mobile: '',
        pass: '',
        tel: '',
        startTime: '',
        endTime: '',
        services: '',
        logo: '',
        address: '',
        username: '',
        intro: '',
        images: []
      },
      uploadUrl: process.env.VUE_APP_UPLOAD_API_URL,
      uploadHeaders: {
        Authorization: localStorage.getItem('token'),
      },
      rules: {
        name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始营业时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束营业时间', trigger: 'change' }],
        services: [{ required: true, message: '请选择服务范围', trigger: 'change' }],
        username: [{ required: true, message: '请输入店主姓名', trigger: 'blur' }],
        intro: [{ required: true, message: '请输入门店介绍', trigger: 'blur' }],
      },
    }
  },
  created() {
    // 获取服务范围列表
    this.getServiceList()
    
    // 检查路由参数，判断是否为编辑模式
    const isEdit = this.$route.query.isEdit
    if (isEdit === 'true') {
      this.isEdit = true
      // 通过API获取门店详细信息
      this.getStoreDetail()
    }
  },
  methods: {
    // 获取门店详细信息
    async getStoreDetail() {
      try {
        const id = this.$route.query.id
        if (!id) return
        
        const res = await getStore({ id })
        const storeData = res.data
        
        this.ruleForm = {
          id: storeData.id || 0,
          name: storeData.name || '',
          mobile: storeData.mobile || '',
          pass: storeData.pass || '',
          tel: storeData.tel || '',
          startTime: storeData.startTime || '',
          endTime: storeData.endTime || '',
          services: storeData.services || '',
          logo: storeData.logo || '',
          address: storeData.address || '',
          username: storeData.username || '',
          intro: storeData.intro || '',
          images: storeData.images || []
        }
        
        // 处理图片显示
        if (this.ruleForm.logo) {
          this.imageUrl = process.env.VUE_APP_UPLOAD_BASE_URL + this.ruleForm.logo
        }
      } catch (error) {
        console.error('获取门店详情失败:', error)
        this.$message.error('获取门店详情失败!')
      }
    },
    
    // 获取服务范围列表
    async getServiceList() {
      try {
        const res = await getServiceList({ page: 1, psize: 1000 })
        this.serviceList = res.data.list || []
      } catch (error) {
        console.error('获取服务范围列表失败:', error)
        this.$message.error('获取服务范围列表失败!')
      }
    },
    
    // 文件
    handleAvatarSuccess(res, file) {
      // 保存图片路径到表单数据中
      this.ruleForm.logo = res.data // 使用返回的数据作为logo路径
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    handleIntroHtml(html) {
      this.ruleForm.intro = html
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 表单
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 无论添加还是编辑都使用add方法
            await add(this.ruleForm)
            this.$message.success(this.isEdit ? '修改成功!' : '添加成功!')
            this.$router.push('/stores')
          } catch (error) {
            this.$message.error(this.isEdit ? '修改失败!' : '添加失败!')
            console.error(this.isEdit ? '修改门店失败:' : '添加门店失败:', error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$router.push('/stores')
    },
  },
}
</script>
<style lang="less" scoped>
/* 文件上传 */
/deep/ .avatar-uploader .el-upload {
  border: 0.1px dashed #d5d5d5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #7e7e7e;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.box-card {
  margin: auto;
  width: 90%;
}

.elinput {
  width: 20%;
}
</style>
